<!--移动版本添加客户信息-->
<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <span>添加客户</span>
        <el-button style="padding: 3px 0" type="text" icon="el-icon-refresh-right" @click=""></el-button>
        <el-button style="float: right; padding: 3px 0" type="text" @click="$router.push('/mobile/mx/addJd')">添加订单</el-button>
      </div>
    <el-form ref="form"  :model="form" :rules="rules2" label-width="5rem">
      <el-form-item v-if="form.userId == undefined" label="客户号" prop="userName">
        <el-input v-model="form.userName" placeholder="客户号【目前无用】" maxlength="30" />
      </el-form-item>
      <el-form-item label="闲鱼名称" prop="nickName">
        <el-input v-model="form.nickName" placeholder="请输入用户昵称（咸鱼名称）" maxlength="30" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phoneNum">
        <el-input v-model="form.phoneNum" placeholder="请输入手机号码" maxlength="11" />
      </el-form-item>
      <el-form-item label="客户类型"  prop="customerType">
        <el-select v-model="form.customerType"  placeholder="请选择客户类型">
          <el-option
            v-for="dict in dict.type.customer_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
      <el-radio-group v-model="form.status">
        <el-radio
          v-for="dict in dict.type.sys_normal_disable"
          :key="dict.value"
          :label="dict.value"
        >{{dict.label}}</el-radio>
      </el-radio-group>
    </el-form-item>
      <el-form-item label="收货地址">
        <el-input v-model="form.address" placeholder="放入收货信息，识别"  >
          <template #append>
            <el-button icon="el-icon-search" @click="identityUserInfo" circle></el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-input v-model="form.province" placeholder="省份" maxlength="11" />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input v-model="form.city" placeholder="城市" maxlength="11" />
      </el-form-item>
<!--
      <el-button type="primary" v-clipboard:copy="'账号:'+form.userName+'  密码:'+form.password" v-clipboard:success="onCopySuccess" v-clipboard:error="onCopyError">复制登陆信息</el-button>
-->
    </el-form>
      <div style="display: flex; justify-content: center; align-items: center; margin-top: 15px;">
        <el-button type="primary" @click="submitForm"  round>添 加</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { deptTreeSelect } from '@/api/system/user'
import { addCustomer, updateCustomer } from '@/api/system/customer'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'AddUserForm',
  dicts: ['sys_normal_disable','customer_type'],
  data() {
    return {
      form: {
        userName: '',
        password: '',
        nickName: '',
        deptId: '',
        phoneNum: '',
        roleIds: [],
        status: '',
        address: ''
      },
      rules2: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: "请选择一个角色(免息券用户选择免息券)", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phoneNum: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      deptOptions: [
        // 部门选项数据
      ],
      roleOptions: [
        // 角色选项数据
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      initPassword: '000000'
    };
  },
  created() {
    this.initForm()
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods:{
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.customerId != undefined) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
            });
          } else {
            this.$set(this.form, 'fishName', this.form.nickName);
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$router.push('/mobile/mx/addJd')
            });
          }
        }
      });
    },
    initForm() {
      this.reset();
      this.$set(this.form, 'customerType', "MX");
      this.title = "快捷生成";
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phoneNum: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        address: undefined,
        postIds: [],
        roleIds: [],//默认选择免息券

      };
      this.resetForm("form");
    },
    onCopySuccess(){
      this.$message.success('信息复制成功')
    },
    onCopyError(){
      this.$message.error('复制失败')
    },
    /**
     * 识别闲鱼信息
     */
    identityUserInfo(){
      if (this.form.address == null || this.form.address == undefined) {
        this.$message.error("请输入收货信息");
        return;
      }

      // 正则表达式匹配用户名和手机号
      const nameRegex = /[\u4e00-\u9fa5]{2,4}/; // 匹配中文名字
      const phoneRegex = /\b1[3-9]\d{9}\b/; // 匹配手机号码

      const nameMatch = this.form.address.match(nameRegex);
      const phoneMatch = this.form.address.match(phoneRegex);

      // 新增正则表达式以匹配省份和城市
      const provinceRegex = /[\u4e00-\u9fa5]{2,10}省/; // 匹配中文省份
      const cityRegex = /[\u4e00-\u9fa5]{2,10}(市|县)/; // 匹配中文城市
      const specialProvinceRegex = /(新疆|西藏|广西|上海|北京|天津|重庆|香港|澳门|台湾)/;
      // 获取省份和城市匹配
      const provinceMatch = this.form.address.match(provinceRegex);
      const cityMatch = this.form.address.match(cityRegex);
      const specialProvinceMatch = this.form.address.match(specialProvinceRegex);

      // 检查是否有匹配的用户名和手机号
      if (nameMatch && phoneMatch) {
        // const userName = nameMatch[0];
        const phoneNum = phoneMatch[0];

        // 提取省份和城市信息
        let city;

        const specialProvinces = ['新疆', '西藏', '广西', '上海', '北京', '天津', '重庆', '香港', '澳门', '台湾'];
        //直辖市
        const specialProvincesCity = [ '上海', '北京', '天津', '重庆'];

        // 获取普通省份匹配并去掉"省"
        let province;
        //是否是直辖市
        let isProvincesCity
        if (specialProvinceMatch) {
          //匹配到特殊省份
          //先看是否也匹配到普通省份，匹配到了，走普通省份逻辑
          if (provinceMatch) {
            province = provinceMatch[0].slice(0, -1) // 普通省份也保留
          } else {
            province = specialProvinceMatch[1]
            isProvincesCity = specialProvincesCity.includes(province)
            if (isProvincesCity) {
              city = province
            }
          }

        } else{
          if (provinceMatch) {
            const rawProvince = provinceMatch[0] // 去掉“省”
            if (specialProvinces.includes(rawProvince)) {
              province = rawProvince // 如果是特殊省份，直接使用
              isProvincesCity = specialProvincesCity.includes(province)
              if (isProvincesCity) {
                city = province
              }
            } else {
              province = rawProvince.slice(0, -1) // 普通省份也保留
            }
          }
        }

          // 如果有城市匹配，提取并处理城市名（去省）
        if (!isProvincesCity && cityMatch) {
          city = cityMatch[0] // 先保留原始城市名
          // 检查城市名是否包含省份，如果包含，去除省份
          if (city.startsWith(province)) {
            city = city.slice(province.length + 1)
          }
          /*  // 检查是否为直辖市，如果是，省份和城市都设置为直辖市名
           const directMunicipalities = ["北京", "天津", "上海", "重庆"];
           if (directMunicipalities.includes(city)) {
             province = city;
           } */
        }

        // 将识别到的信息存储到数据中，供后续使用
        this.form.userName =  this.generateShortUUID(); // 使用 UUID
        this.form.phoneNum = phoneNum;
        this.$set(this.form, 'province', province);
        this.$set(this.form, 'city', city);

        //this.address = address;
      } else {
        // 未能识别到用户名和手机号
        alert('无法识别用户名和手机号');
      }
    },

    /**
     * 生成uuid来当做登录账户
     * @returns {string}
     */
    generateShortUUID() {
      return 'xxxxxxxxxxxxxxxx'.replace(/x/g, () => {
        return Math.floor(Math.random() * 16).toString(16);
      });
    }

  }
}
</script>

<style scoped>

</style>
